export const useAuthStore = defineStore('auth', () => {
  // 权限判断
  const hasPolicy = async (payload) => {
    const { sub, obj, act } = payload
    if (isNilOrEmpty(sub)) { return { msg: '必传参数sub未传' } }
    if (isNilOrEmpty(obj)) { return { msg: '必传参数obj未传' } }
    if (isNilOrEmpty(act)) { return { msg: '必传参数act未传' } }
    const { data } = await Fetch('/api/casbin/hasPolicy', { method: 'post', data: { sub, obj, act } })
    return data
  }
  // 批量权限判断
  const hasPolices = async (payload) => {
    if (!isArray(payload) || isNilOrEmpty(payload)) { return { msg: '传参错误' } }
    const { sub, obj, act } = payload[0]
    if (isNilOrEmpty(sub)) { return { msg: '必传参数sub未传' } }
    if (isNilOrEmpty(obj)) { return { msg: '必传参数obj未传' } }
    if (isNilOrEmpty(act)) { return { msg: '必传参数act未传' } }
    const { data } = await Fetch('/api/casbin/hasPolicies', { method: 'post', data: payload })
    return data
  }
  const addPolicy = async (payload) => {
    const { sub, obj, act } = payload
    if (isNilOrEmpty(sub)) { return { msg: '必传参数sub未传' } }
    if (isNilOrEmpty(obj)) { return { msg: '必传参数obj未传' } }
    if (isNilOrEmpty(act)) { return { msg: '必传参数act未传' } }
    const { data } = await Fetch('/api/casbin/addPolicy', { method: 'post', data: { sub, obj, act } })
    return data
  }
  const addPolicies = async (payload) => {
    const { data } = await Fetch('/api/casbin/addPolicies', { method: 'post', data: payload })
    return data
  }
  const removePolicy = async (payload) => {
    const { sub, obj, act } = payload
    if (isNilOrEmpty(sub)) { return { msg: '必传参数sub未传' } }
    if (isNilOrEmpty(obj)) { return { msg: '必传参数obj未传' } }
    if (isNilOrEmpty(act)) { return { msg: '必传参数act未传' } }
    const { data } = await Fetch('/api/casbin/removePolicy', { method: 'delete', data: { sub, obj, act } })
    return data
  }
  // 获取单个角色所有acts
  const getRoleActs = async (roleCode, act) => {
    const payload = {
      sub: { index: 0, value: roleCode },
      act: { index: 3, value: act },
    }
    const roleList = await getSubActs(payload)
    if (isNilOrEmpty(roleList)) { return [] }
    return roleList.map(e => e[2])
  }
  // 获取符合 sub, act 的数据。payload 格式：{sub:{index:0,value:'roleId'}, act:{index:3, value:'POLICY_NAME'}}
  const getSubActs = async (payload) => {
    const { status, data } = await Fetch('/api/casbin/getPolicies', { method: 'post', data: payload })
    if (status !== 200 || data.code !== 0) { return [] }
    return data.result ?? []
  }
  // 更新权限列表: 会自动判断
  const updateRolePolicies = async (sub, act, reqData) => {
    const { status, data } = await Fetch('/api/casbin/updatePolicies', { method: 'post', data: { sub, act, objs: reqData } })
    if (status !== 200 || data.code !== 0) {
      message.error(data.msg)
      return
    }
    return data.result
  }
  let permissions = $ref([])
  let roles = $ref([])
  // 获取拥有某个按钮权限的所有角色列表
  const getPolicyRoles = async (menuPath, authCode) => {
    const payload = {
      sub: { index: 2, value: menuPath },
      act: { index: 3, value: authCode },
    }
    const roleList = await getSubActs(payload)
    if (isNilOrEmpty(roleList)) {
      return
    }
    const role_code = roleList.map(e => e[0]).join(',')
    const { status, data } = await Fetch('/api/s/t/auth_role',
      {
        method: 'post',
        headers: { timestamp: Date.now() },
        data: { role_code, limit: 500 },
      })
    if (status !== 200 || data.code !== 0) {
      message.error(data.msg)
      return
    }
    return data.result.dataList
  }
  // 获取用户权限列表
  const getUserPermissions = async () => {
    const { status, data } = await Fetch('/api/casbin/getPermissionsForUser')
    if (status !== 200 || data.code !== 0) {
      message.error(data.msg)
      return
    }
    permissions = data.result.permissions
    roles = data.result.roles
  }
  // 判断用户权限
  const can = computed(() => (sub, act) => {
    if (isNilOrEmpty(permissions) || isNilOrEmpty(roles)) { return false }
    return permissions.some(e => e[2] === sub && e[3] === act)
  })

  return {
    hasPolicy,
    hasPolices,
    addPolicy,
    addPolicies,
    removePolicy,
    getRoleActs,
    getSubActs,
    getPolicyRoles,
    updateRolePolicies,
    getUserPermissions,
    can,
  }
}, { unistorage: { key: 'config-auth' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useAuthStore, import.meta.hot))
